package cn.jinbyte.core.utils;

import lombok.experimental.UtilityClass;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * AOP工具类
 *
 * @author jinty
 * @since 2024/12/1
 */
@UtilityClass
public class AopUtils {
    /**
     * 获取方法或类上的指定注解
     *
     * @param joinPoint       query point
     * @param annotationClass 注解类
     * @param <T>             注解类型
     * @return 注解实例
     */
    public static <T extends Annotation> T getAnnotationOnMethodOrClass(JoinPoint joinPoint, Class<T> annotationClass) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        T annotation = null;
        if (method != null) {
            annotation = method.getAnnotation(annotationClass);
        }
        if (annotation != null) {
            return annotation;
        }
        // 获取类上的注解
        Class<?> targetClass = joinPoint.getTarget().getClass();
        return targetClass.getAnnotation(annotationClass);
    }

    /**
     * 获取方法上的指定注解
     *
     * @param joinPoint       query point
     * @param annotationClass 注解类
     * @param <T>             注解类型
     * @return 注解实例
     */
    public static <T extends Annotation> T getAnnotationOnMethod(JoinPoint joinPoint, Class<T> annotationClass) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        T annotation = null;
        if (method != null) {
            return method.getAnnotation(annotationClass);
        }
        return null;
    }
}